//
//  HMStatusPictureView.swift
//  HMWeibo1
//
//  Created by liGordon on 16/4/14.
//  Copyright © 2016年 lifuli. All rights reserved.
//

import UIKit

/// collectionViewCell的间距
private let HMStatusPictureViewCellMargin: CGFloat = 4

/// cell的最大列数为3列(整数)
private let HMStatusPictureViewMaxColumn = 3

/// 计算cell的宽和高
private let HMStatusPictureViewItemWH = (UIScreen.mainScreen().bounds.width - 2 * HMStatusCellMargin - (CGFloat(HMStatusPictureViewMaxColumn) - 1) * HMStatusPictureViewCellMargin) / CGFloat(HMStatusPictureViewMaxColumn)

class HMStatusPictureView: UICollectionView {

  //  private var layout = UICollectionViewFlowLayout()
  
    /// 配图NSURL数组
    
    var pictureURLs: [NSURL]? {
    didSet {
    // 当别人设置配图的URL后,我们就来计算配图的高度
    
    let size = calculateViewSize()
    
    // 自己来约束大小 当cell给pictureURLS之后计算出宽高然后重新修改约束
    
    self.snp_updateConstraints { (make) -> Void in
        make.size.equalTo(size)
        }
        HMPrint("配图大小: \(size)")
        
    }
    }
    
    
    /// 计算配图的宽高
    private func calculateViewSize() -> CGSize {
        // 设置collectionView layout
        layout.itemSize = CGSize(width: HMStatusPictureViewItemWH, height: HMStatusPictureViewItemWH)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        // 判断图片的数量
        let count = pictureURLs?.count ?? 0
        
        // 没有图片
        if count == 0 {
            HMPrint("没有图片")
            return CGSizeZero
        }
        
        // 1张图片
        if count == 1 {
            // TODO: 返回图片本来的大小
            let size = CGSize(width: 180, height: 90)
            layout.itemSize = size
            return size
        }
        
        layout.minimumLineSpacing = HMStatusPictureViewCellMargin
        layout.minimumInteritemSpacing = HMStatusPictureViewCellMargin
        
        // 多张图片 列数不确定
        //2张4张图片显示2列 其他都3列
        var column = HMStatusPictureViewMaxColumn
        if count == 2 || count == 4 {
            column = 2
        }
        // 行数 = (总个数 + 列数 -1 )/ 列数
        let row = (count + column - 1) / column
        
        // 计算宽度和高度
        // 宽度 = 列数 * item宽度 + (列数 - 1) * 列间距
        let widht = CGFloat(column) * HMStatusPictureViewItemWH + (CGFloat(column) - 1) * HMStatusPictureViewCellMargin
        
        // 高度度 = 行数 * item高度 + (行数 - 1) * 行间距
        let height = CGFloat(row) * HMStatusPictureViewItemWH + (CGFloat(row) - 1) * HMStatusPictureViewCellMargin
        return CGSize(width: widht, height: height)
    }
    
    private var layout = UICollectionViewFlowLayout()

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
 
     }
    
}
